﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Linq;

public class StageObject : IStage
{
    private Dictionary<int, IWorldObject> worldObjs = new Dictionary<int, IWorldObject>();

    private List<int> removeObjIds = new List<int>();

    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="deltaTime"></param>
    public override void Update(float deltaTime)
    {
        foreach (int id in removeObjIds)
        {
            worldObjs.Remove(id);
        }

        foreach (IWorldObject obj in worldObjs.Values)
        {
            obj.Update(deltaTime);
        }
    }

    /// <summary>
    /// 添加WorldObject
    /// </summary>
    /// <param name="worldObj"></param>
    public override void AddWorldObj(IWorldObject worldObj)
    {
        int id = worldObj.GetId();
        if (!worldObjs.ContainsKey(id))
        {
            worldObjs.Add(id, worldObj);
        }
    }

    /// <summary>
    /// 移除WorldObject
    /// </summary>
    /// <param name="id"></param>
    public override void RemoveWorldObj(int id)
    {
        removeObjIds.Add(id);
    }

    /// <summary>
    /// 获取WorldObject
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public override IWorldObject GetWorldObj(int id)
    {
        if (worldObjs.ContainsKey(id))
        {
            return worldObjs[id];
        }

        return null;
    }

    /// <summary>
    /// 存在WorldObject
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public override bool HasWorldObj(int id)
    {
        return worldObjs.ContainsKey(id);
    }

    public override List<T> GetObjs<T>()
    {
        List<T> objs = new List<T>();
        foreach (IWorldObject worldObj in worldObjs.Values)
        {
            if (worldObj is T)
            {
                objs.Add((T)((object)worldObj));
            }
        }

        return objs;
    }

    public override T GetObj<T>(int id)
    {
        if (worldObjs.ContainsKey(id))
        {
            IWorldObject worldObj = worldObjs[id];

            if (worldObj is T)
            {
                return (T)((object)worldObj);
            }
        }

        return default(T);
    }
}
